//切换左侧菜单的显示和隐藏
function toggleMenu() 
{
    const submenu = document.getElementById("submenu");
    const arrow = document.getElementById("arrow");

    //切换显示状态
    submenu.style.display = submenu.style.display === "none" ? "block" : "none";
    //根据菜单状态更新箭头符号
    arrow.textContent = submenu.style.display === "block" ? "▲" : "▼";
}
//切换显示内容区域
function showContent(sectionId) 
{
    const sections = document.querySelectorAll('.content-section');
    sections.forEach(section => section.style.display = 'none');
    document.getElementById(sectionId).style.display = 'block';
}

function createUser() 
{
    const username = document.getElementById('username').value;
    const password = document.getElementById('password').value;
    const email = document.getElementById('email').value;
    //console.log("已经得到的邮箱地址是:",email);

    if (username && password) {
        fetch('/createuser', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ username: username, password: password, email: email})
        })
        .then(response => {
            if (response.ok) {
                alert("创建新用户成功!");
                //重新开始
                document.getElementById('createUserForm').reset();
            } else {
                alert("用户创建失败！");
            }
        })
        .catch(error => console.error("创建用户出错：", error));
        //console.log("新用户已创建: ", username, password);
        //alert("用户已创建！");
        //document.getElementById('createUserForm').reset();
    } 
    else 
    {
        alert("请输入用户名和密码！");
    }
}

function createRoom() 
{
    const name = document.getElementById('roomname').value;
    const ownerid = document.getElementById('roomcreateid').value;
    const capacity = document.getElementById('roomcapacity').value;
    const description = document.getElementById('roomdesc').value;

    if (name && ownerid && capacity ) {
        fetch('/createroom', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ name: name, ownerid: ownerid, capacity: capacity,description: description})
        })
        .then(response => {
            if (response.ok) {
                alert("创建新房间成功!");
                //重新开始
                document.getElementById('createRoomForm').reset();
            } else {
                alert("房间创建失败！");
            }
        })
        .catch(error => console.error("创建房间出错：", error));
    }
    else
    {
        alert("请输入房间相关信息,不能为空！");
    }
}
////////////////////////////////////////////////
//BEGIN:加载用户信息的代码
function loadUsers() {
    fetch('/api/users')
        .then(response => response.json())
        .then(users => {
            const tbody = document.getElementById('userTable').getElementsByTagName('tbody')[0];
            tbody.innerHTML = ''; // 清空表格内容

            //这里转换好的user是一个josn的结构，所以是可以用下面的user.id来访问，在java里它是么有成员。
            users.forEach(user => {
                const row = tbody.insertRow();
                row.insertCell(0).innerText = user.id;
                row.insertCell(1).innerHTML = `<input type="text" value="${user.username}" id="username-${user.id}">`;
                row.insertCell(2).innerHTML = `<input type="text" value="${user.roomid}" id="roomid-${user.id}">`;
                row.insertCell(3).innerHTML = `<input type="text" value="${user.email}" id="email-${user.id}">`;
                row.insertCell(4).innerHTML = `<button class="submit-btn" onclick="updateUser(${user.id})">保存</button>`;
            });
        })
        .catch(error => console.error('获取用户失败:', error));
}
//更新修改过的数据。
function updateUser(id) {
    const username = document.getElementById(`username-${id}`).value;
    const email = document.getElementById(`email-${id}`).value;
    const roomid = document.getElementById(`roomid-${id}`).value;
    //const password = prompt("请输入新的密码（如果不想修改密码，请留空）");
    // 创建请求体
    const updatedUser = {
        username: username,
        email: email,
        roomid: roomid
        //password: password ? password : null
    };
    fetch(`/api/users/${id}`, {
        method: 'PUT',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(updatedUser)
    })
    .then(response => {
        if (response.ok) {
            alert("用户信息已更新");
            loadUsers(); // 刷新表格
        } else {
            alert("更新用户失败");
        }
    })
    .catch(error => console.error('更新用户失败:', error));
}
//END:加载用户信息的代码

////////////////////////////////////////////////
//BEGIN:加载房间信息的代码
function loadRooms() {
    fetch('/api/rooms')
        .then(response => response.json())
        .then(rooms => {
            const tbody = document.getElementById('roomTable').getElementsByTagName('tbody')[0];
            tbody.innerHTML = ''; // 清空表格内容

            rooms.forEach(room => {
                const row = tbody.insertRow();
                row.insertCell(0).innerText = room.id;
                row.insertCell(1).innerHTML = `<input type="text" value="${room.name}" id="name-${room.id}">`;
                row.insertCell(2).innerHTML = `<input type="text" value="${room.ownerid}" id="ownerid-${room.id}">`;
                row.insertCell(3).innerHTML = `<input type="text" value="${room.capacity}" id="capacity-${room.id}">`;
                row.insertCell(4).innerHTML = `<input type="text" value="${room.description}" id="description-${room.id}">`;
                row.insertCell(5).innerHTML = `<button class="submit-btn" onclick="updateRoom(${room.id})">保存</button>`;
            });
        })
        .catch(error => console.error('获取房间失败:', error));
}
//更新修改过的数据。
function updateRoom(id) {
    const name = document.getElementById(`name-${id}`).value;
    const ownerid = document.getElementById(`ownerid-${id}`).value;
    const capacity = document.getElementById(`capacity-${id}`).value;
    const description = document.getElementById(`description-${id}`).value;

    const updatedRoom = {
        name: name,
        ownerid: ownerid,
        capacity: capacity,
        description: description
    };
    fetch(`/api/rooms/${id}`, {
        method: 'PUT',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(updatedRoom)
    })
    .then(response => {
        if (response.ok) {
            alert("房间信息已更新");
            loadRooms();
        } else {
            alert("更新房间失败");
        }
    })
    .catch(error => console.error('更新房间失败:', error));
}
//END:加载房间信息的代码
document.addEventListener("DOMContentLoaded", loadUsers);//页面加载时加载用户数据
document.addEventListener("DOMContentLoaded", loadRooms);//页面加载时加载房间数据